package middlewares

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"shop_srv_api/user_web/global"
	"shop_srv_api/user_web/models"
)

/**
 * @Description
 * @Author huran
 * @Date
 * @Param
 * @return
 **/

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("x-token")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"msg": "请登录",
			})
			c.Abort()
			return
		}
		j := NewJWT()
		claims, err := j.ParseToken(token)
		if err != nil {
			if err == TokenExpired {
				c.JSON(http.StatusUnauthorized, gin.H{
					"msg": "授权已过期",
				})
				c.Abort()
				return
			}
			c.JSON(http.StatusUnauthorized, gin.H{
				"msg": "未登录",
			})
			c.Abort()
			return
		}
		c.Set("claims", claims)
		c.Set("userId", claims.ID)
		c.Next()
	}
}

type JWT struct {
	SigningKey []byte
}

var (
	TokenExpired     = errors.New("")
	TokenNotValidYet = errors.New("")
	TokenMalFormed   = errors.New("")
	TokenInvalid     = errors.New("")
)

func NewJWT() *JWT {
	return &JWT{SigningKey: []byte(global.ServerConfig.JwtConfig.SigningKey)}
}

func (j *JWT) CreateToken(claims models.CustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
	return token.SignedString(j.SigningKey)
}
func (j *JWT) ParseToken(tokenString string) (*models.CustomClaims, error) {
	claims, err := jwt.ParseWithClaims(tokenString, &models.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return j.SigningKey, nil
	})
	if err != nil {
		var v *jwt.ValidationError
		if errors.As(err, &v) {
			if v.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalFormed
			}
			if v.Errors&jwt.ValidationErrorExpired != 0 {
				return nil, TokenExpired
			}
			if v.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			}
			return nil, TokenInvalid
		}
	}
	return claims.Claims.(*models.CustomClaims), err
}
